package com.usvisatrack.services.common;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.usvisatrack.core.common.Factory;

/**
 * Main entry point for all data crawl services. The class name is passed to this class in order to execute a service.
 * 
 * @author YuCheng Hu
 *
 */
public class Main {
	private static Options options = new Options();
	private static Logger log = LoggerFactory.getLogger(Main.class);
	private static CommandLine cl = null;

	/**
	 * Determines whether or not he service launcher encountered an error while trying to launch the service.
	 */
	public static boolean error = false;

	/**
	 * Main entry point for the service launcher.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// configure command line options
		Main.options.addOption("c", true, "The name of the class to execute, relative to the com.verani.services package.");

		// parse command line options
		CommandLineParser parser = new GnuParser();

		try {
			Main.cl = parser.parse(Main.options, args, true);

			// get the class
			Class<?> clazz = Class.forName("com.usvisatrack.services." + Main.cl.getOptionValue("c"));
			DataCrawl dataCrawl = (DataCrawl) clazz.newInstance();

			// set up the command line
			dataCrawl.parseCommandLine(Main.cl.getArgs());
			dataCrawl.run();

			Factory.close();
		} catch (Exception ex) {
			Main.log.error("An error occurred starting the specified service (" + Main.cl.getOptionValue("c") + ")", ex);
			Main.error = true;
		}
	}
}
